#!/usr/bin/perl

##HACKABOT_HELP##
# Recommends a place you should go.
# __NAME__ [ add <place> | noun <item> | adj <description> ]
##HACKABOT_HELP##

# This was based on Scott's lunchalizer irssi script/bot
# but hacked to hell and has little relation now.

use strict;
use File::Basename;
use Hackabot::Client;

$0 = basename($0); 

sub make_lunch {
    my ($hbc, $dbh, $sth, @row, $lunch, $time);

    $hbc = Hackabot::Client->new;
    $dbh = $hbc->dbi() or die "Failed to connect to database\n";

    $time = `date "+%y%m%d%H%M"`;
    chomp $time;
    $time = $dbh->quote($time);

    $sth = $dbh->prepare("SELECT id, name FROM $0_location
                          ORDER BY RAND()*(1/lastused) DESC LIMIT 1");
    $sth->execute;
    if (@row = $sth->fetchrow_array) {
        $lunch = "suggests " . $row[1] . " for";
        my $id = $dbh->quote($row[0]);
        $dbh->do("UPDATE $0_location SET lastused = $time WHERE id = $id");
    }
    else {
        return "suggests nothing"
    }

    $sth = $dbh->prepare("SELECT name FROM $0_adj ORDER BY RAND() LIMIT 1");
    $sth->execute;
    if (@row = $sth->fetchrow_array) {
        $lunch .= " " . $row[0];
    }

    $sth = $dbh->prepare("SELECT name FROM $0_noun ORDER BY RAND() LIMIT 1");
    $sth->execute;
    if (@row = $sth->fetchrow_array) {
        $lunch .= " " . $row[0];
    }
    else {
        $lunch .= " something";
    }

    $dbh->disconnect;
    return $lunch;
}

sub add {
    my ($thing, $item) = @_;
    my ($hbc, $dbh, $sth, $ret);

    $hbc = Hackabot::Client->new;
    $dbh = $hbc->dbi() or die "Failed to connect to database\n";

    $sth = $dbh->prepare("INSERT INTO $0_$thing(name) VALUES (?)");

    if ($sth->execute($item)) {
        $ret = "Successfully added $item";
    } elsif ($dbh->err == 1062) {
        $ret = "I already have $item";
    } else {
        $ret = "I failed to add $item";
    }

    $dbh->disconnect;
    return $ret;
}

$_ = <>;

if (/^$/) {
	print "me ".make_lunch();
}
elsif (/^add\s+(\S+.*)$/) {
	print "send ".add("location", $1);
}
elsif (/^noun\s+(\S+.*)$/) {
	print "send ".add("noun", $1);
}
elsif (/^adj\s+(\S+.*)$/) {
	print "send ".add("adj", $1);
}
